﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Commands.Settings;

namespace Commands.TorrentDownloaders
{
    /// <summary>
    /// Class for managing torrent issues. 
    /// </summary>
    public class TorrentManager : ITorrentManager
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="settings">Tracking services settings.</param>
        /// <remarks>Dispatcher idea and code has been taken from: http://utorrentremote.codeplex.com/ 
        /// Read article about it at http://habrahabr.ru/blogs/p2p/116544/ </remarks>
        public TorrentManager(TrackerServiceSettings settings, string defaultDownloadFolder)
        {
            _dispatchers = new List<ITokenDispatcher>();
            _dispatchers.Add(new FreeTorrentsDownloadDispatcher(settings.FreeTorrents));
            _dispatchers.Add(new RuTrackerDownloadDispatcher(settings.RuTracker));
            _dispatchers.Add(new TapochekNetDownloadDispatcher(settings.TapochekNet));

            _mapping = settings.FoldersMapping;

            _defaultFolder = defaultDownloadFolder;
        }

        /// <summary>
        /// Download torrent file from url and add torrent to utorrent.
        /// </summary>
        public bool TryDownload(string url, string dirParam, string mapping)
        {
            var downloadFolder = _GetDownloadFolder(dirParam, mapping);

            return _dispatchers.Any(dispatcher => dispatcher.CheckTokenCanBeDownloaded(url, downloadFolder));
        }

        private string _GetDownloadFolder(string dirParam, string mapping)
        {
            if (!string.IsNullOrEmpty((dirParam)))
                return dirParam;

            var foundMapping =
                _mapping.FirstOrDefault(y => string.Compare(y.Name, mapping, StringComparison.OrdinalIgnoreCase) == 0);

            return foundMapping != null ? foundMapping.Folder : _defaultFolder;
        }

        /// <summary>
        /// Start bittorrent.
        /// </summary>
        /// <param name="filePath">Torrent file path.</param>
        /// <param name="directory">Directory to save content.</param>
        public static bool StartTorrent(string filePath, string directory)
        {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
                throw new ArgumentException("filePath");
            if (string.IsNullOrEmpty(directory))
                throw new ArgumentException("directory");

            var fileInfo = new FileInfo(filePath);

            var process = new Process
            {
                StartInfo =
                {
                    FileName = ProgrammsFinder.GetTorrentClientPath(),
                    Arguments = string.Format("/DIRECTORY {0} {1}", directory, fileInfo.FullName)
                }
            };
            process.Start();

            return true;
        }

        private readonly List<ITokenDispatcher> _dispatchers;
        private readonly List<Mapping> _mapping;
        private readonly string _defaultFolder;
    }
}
